<template>
  <div id="group">
    <el-row class="bgColor">
      <el-col :xs="24" :sm="24" :lg="24" class="toFlex">
        <div class="item">
          <label for="cascader">选择项目:</label>
          <el-cascader
            clearable
            placeholder="Yorkdale"
            :options="selector"
            filterable
            :show-all-levels="false"
            :collapse-tags="isMultiple ? true : false"
            v-model="selected"
            @change="toChange"
            :props="{ multiple: isMultiple }"
            style="margin-left: 10px; width:12%"
            id="cascader"
            :class="{'mwidth': isMultiple}"
            >
          </el-cascader>
          
          <label v-if="isShow" for="weeks" style="margin:auto 15px;">选择周:</label>
          <el-date-picker
            id="weeks"
            style="margin: auto 0;"
            @change="changeWeek"
            v-if="isShow"
            v-model="weeks"
            type="week"
            format="yyyy 第 WW 周"
            :picker-options="{'firstDayOfWeek': 1}"
            placeholder="选择周">
          </el-date-picker>

          <label v-if="isShow" for="levels" style="margin:auto 15px;">风险等级:</label>
          <el-select style="margin: auto 0;" @change="changeLevel" v-if="isShow" clearable multiple v-model="levels" placeholder="请选择风险等级">
            <el-option
              v-for="item in levelsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>        
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { mapState, mapMutations } from 'vuex'
  import http from '@/views/sys/axios'
  import Moment from 'moment'
  
  export default {
    name: 'Group',
    props: {
      isMultiple: {
        type: Boolean,
        default: false
      },
      isShow: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      ...mapState({
        dispose: state => state.conditions.dispose
      })
    },
    
    watch: {
      selected(newData){
          this.setGroupXzxm()
      }
    },
    created () {
      this.getOptionsResult()
      this.getTabledata()
    },
    data() {
      return {
        proIdListArr:[],
        current:1,
        selector: [],
        selected: null,
        weeks: '',
        levels: [],
        levelsOptions: [
          {
            value: 3,
            label: '高风险'
          },
          {
            value: 2,
            label: '中风险'
          },
          {
            value: 1,
            label: '低风险'
          }
        ]
      }
    },
    methods: {

      ...mapMutations(['setGroupXzxm']),
      
      getTabledata(){
        const self = this
            let data = {}
            data.project_id = this.proIdListArr
            console.log(data.project_id)
             http.post(`/api/report/project/weekly/report/highlight/data?page=${self.current}`, data)
             .then(res => {
              self.loading = true
              const { code, result, count } = res
              if(code === 200) {
                console.log(222,res.result)
                let list = result
                self.loading = false
                self.tableData = list
                this.$emit('func',list)
                self.total = count
                console.log("self.tableData",self.tableData)
              }
            })
      },
      ...mapMutations('conditions', [
        'setDispose'
      ]),
      changeWeek(val) { 
        // let year, week, yearWeek
        // if(val != null) {
        //   year = new Date(val).getFullYear()
        //   week = Moment(this.weeks).utcOffset(480).format("WW") 
        //   yearWeek = `${year}-${week}`  
        // } else {
        //   yearWeek = ''
        // }
        // this.setDispose({
        //   weeks: yearWeek
        // }) 
      },
      changeLevel(val) {
        // this.setDispose({
        //   levels: this.levels
        // })
      },
      async statusChange(val) {
        try {
          const { code, project_list } = await this.getOptions()
          if(code === 200) {
            this.selector = project_list
            let item2, item3, all = [], id        
            const val1 = this.selector[0].value
            if(Array.isArray(project_list) && project_list.length) {        
              project_list[0].children.forEach(list2 => {
                item2 = list2.value
                list2.children.forEach(list3 => {
                  item3 = list3.value 
                  all.push([val1, item2, item3])              
                })             
              })          
            }
            this.selected = all
            id = this.computeMultiple(project_list, this.selected)
            this.setDispose({
              optionsList: this.selected,
              projectIdList: id
            })
            // this.computeInit(project_list)   
          }
        } catch(err) {
          throw err
        }
      },
      getOptions() {
        return http.get(`/api/data_summary/car/project/list`)
      },
      async getOptionsResult() {
        try {
          const { code, project_list } = await this.getOptions()          
          if(code === 200) {
            this.selector = project_list            
            if(this.isMultiple) { // 多选状态下的处理逻辑
              if(this.dispose.optionsList.length) {                           
                this.selected = this.dispose.optionsList
              } else {
                this.computeInit(project_list)            
              }
            } else { // 单选状态下的处理逻辑
              if(this.dispose.options.length) {
                this.selected = this.dispose.options
              } else {
                this.computeInit(project_list)
              }
            }
            let val = JSON.parse(localStorage.getItem('tmpval'))
            let valueList = JSON.parse(localStorage.getItem('tmpvalueList'))
            this.selected = val
          }
        } catch (err) {
          throw new Error(err)
        }

      },
      computeInit(project_list) {
        // const val1 = this.selector[0].value
        const val2 = this.selector[0].children[0].value
        const val3 = this.selector[0].children[0].children[0].value
        let item2, item3, all = []        
        const val1 = this.selector[0].value
        if(Array.isArray(project_list) && project_list.length) {        
          project_list[0].children.forEach(list2 => {
            item2 = list2.value
            list2.children.forEach(list3 => {
              item3 = list3.value 
              all.push([val1, item2, item3])              
            })             
          })          
        }        
        
        let id = null
        if(this.isMultiple) {
          // 获取首次进入的ID 全选
          this.selected = all //[[val1, val2, val3]]
          
          id = this.computeMultiple(project_list, this.selected)
          this.setDispose({
            optionsList: this.selected,
            projectIdList: id
          })
        } else {
          // 获取首次进入的ID
          this.selected = [val1, val2, val3]
          id = this.computeCondition(project_list, this.selected)
          this.setDispose({
            options: this.selected,
            projectId: id
          })
        }    
      },
      computeCondition(list, filter) {
        if(Array.isArray(list) && !list.length) {
          return []
        }
        const outer = list.filter(item => item.value === filter[0]) // 事业群
        let mider = [] // 事业部
        let inner = [] // 项目
          
        if(outer[outer.length - 1].children) {
          let miderList = outer[outer.length - 1].children
          mider = miderList.filter(item => item.value === filter[1])
          
          if(mider[mider.length - 1].children) {
            let innerList = mider[mider.length - 1].children
            inner = innerList.filter(item => item.value === filter[2])
          }
        }               
        const { value } = inner[0]
        return value
      },
      computeMultiple(list, filter) {
        if(Array.isArray(list) && !list.length) {
          return []
        }
        let multipleArr = []
        filter.forEach(item => {
          multipleArr.push(this.computeCondition(list, item))
        })
        return multipleArr
      },
      toChange(val) {  
        let proIdList = []
        val.forEach(item => {
            proIdList.push(item[2])
        })
        this.proIdListArr = proIdList
        this.getTabledata()
        let arr = this.selector
        if(this.isMultiple) {
        //   let valueList = this.computeMultiple(arr, val)
        //   localStorage.setItem('tmpval', JSON.stringify(val))
        //   localStorage.setItem('tmpvalueList', JSON.stringify(valueList))

        //   this.setDispose({
        //     optionsList: val,
            // projectIdList: valueList
        //   })
        }
        //  else {          
        //   let value = this.computeCondition(arr, val)
        //   this.$emit('getson', val[2]) 
        //   // console.log('我向父组件发射了一个事件', val[2]);

        //   this.setDispose({
        //     options: val,
        //     projectId: value
        //   })
          
        // }    
      }
    },
  }
</script>

<style lang="scss" scoped>
  
  #group{
    .bgColor{
      background: #ffffff;
      padding: 20px;
      .toFlex{
        display: flex;
        .item{
          display: flex;
          flex: 1;
          label{
            margin: auto 0;
          }
          #cascader, #selectd{
            margin: auto 0;
            width: 20%;
            &.mwidth{
              width: 23%;
            }
          }
          .item2{
            margin-left: 20px;
          }
        }
      }
    }

  }
  @media screen and (max-width: 1440px){
    #group .bgColor .toFlex .item #cascader.mwidth{
      width: 25%;
    }
  }
</style>